<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import LuckyExcel from 'luckyexcel'
import index from "@/components/analysisSheetComponents/gufei/tmpl104/index.vue";
import {useAnalysetStore} from "@/store/index";
import {getUserInfo} from "@/utils/auth";
import {filterValidSampleAdatas, filterValidSamples, processTableData, transformData} from "@/utils/method";
import AnalyesAPI from "@/api/system/analyes";
import CommonAPI from "@/api/common/index";
import Index from "@/components/analysisSheetComponents/component/index.vue";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "column": 10, // 列数
      "defaultRowHeight": 30, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "类型",}, // A1
        {"r": 0, "c": 2, "v": "取样体积 V (mL)	",}, // B1
        {"r": 0, "c": 3, "v": "消解后定容体积V₀ (mL)",}, // B1
        {"r": 0, "c": 4, "v": "分取体积V₁ (mL)",}, // B1
        {"r": 0, "c": 5, "v": "分取后定容体积V₂ (mL)",}, // B1
        {"r": 0, "c": 6, "v": "稀释倍数f",}, // B1
        {"r": 0, "c": 7, "v": "样品浓度ρ₁-ρ₀(μg /L)",}, // B1
        {"r": 0, "c": 8, "v": "浸出液的含量ρ(μg /L)",}, // B1
        {"r": 0, "c": 9, "v": "测定结果",}, // B1
        {"r": 0, "c": 10, "v": "备注",}, // B1
      ], // 初始化数据
      "config": {
        "merge": {}, // 合并单元格
        "columnlen": { // 设置列宽
          "0": 130, // 第一列宽度 150px
          "1": 130, // 第二列宽度 120px
          "2": 130, // 第三列宽度 180px
          "3": 130, // 第四列宽度 100px
          "4": 130, // 第五列宽度 200px
          "5": 130,  // 第六列宽度 150px
          "6": 130,  // 第六列宽度 150px
          "7": 130,  // 第六列宽度 150px
          "8": 130,  // 第六列宽度 150px
          "9": 130,  // 第六列宽度 150px
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const switchAB = ref(true)
const sheetData = ref('')
const jsonData = ref(null)
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const processedData = ref([])
const cdatas = ref([])
const checkDialogVisible = ref(false)
const checkTime = ref('')
const userInfo = JSON.parse(getUserInfo())
const waterForm = ref({
  bdatas: {
    qxpz: [
      {
        qx_ys: '',
        qx_zbyph: '',
        qx_zbynd: '',
        zbyyxrq: '',
        qx_zbytj: '',
        qx_drtj: '',
        qx_zjynd: '',
        qx_yqzjytj: '',
        qx_drtj1: '',
        qx_syynd: '',
        qx_bz: '',
      },
      {
        qx_ys: '',
        qx_zbyph: '',
        qx_zbynd: '',
        zbyyxrq: '',
        qx_zbytj: '',
        qx_drtj: '',
        qx_zjynd: '',
        qx_yqzjytj: '',
        qx_drtj1: '',
        qx_syynd: '',
        qx_bz: '',
      },
    ],
    bzsyyjrl: {},
    syynd: {},
    xyz: {},
    qxjhdcd: [
      {qx_ypbh: '', qx_xdwc: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_xdwc: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_xdwc: '', qx_zkyq: '', qx_sfhg: ''},
      {qx_ypbh: '', qx_xdwc: '', qx_zkyq: '', qx_sfhg: ''},
    ],
  },
  pxycd: Array.from({length: 8}, () => ({
    px_ys: '', px_ypbh: '', px_cdnd: '', px_pjz: '',
    px_xdwc: '', px_zkbz: '', px_sfhg: ''
  })),
  bzycd: [
    {bz_ys: '', bz_bzph: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
    {bz_ys: '', bz_bzph: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
  ],
  jbycd: [
    {
      jb_ys: '',
      jb_ypbh: '',
      jb_jbhypnd: '',
      jb_bynd: '',
      jb_jbl: '',
      jb_yyphl: '',
      jb_jbhsl: '',
      jb_zkyq: '',
      jb_sfhg: ''
    },
    {
      jb_ys: '',
      jb_ypbh: '',
      jb_jbhypnd: '',
      jb_bynd: '',
      jb_jbl: '',
      jb_yyphl: '',
      jb_jbhsl: '',
      jb_zkyq: '',
      jb_sfhg: ''
    },
    {
      jb_ys: '',
      jb_ypbh: '',
      jb_jbhypnd: '',
      jb_bynd: '',
      jb_jbl: '',
      jb_yyphl: '',
      jb_jbhsl: '',
      jb_zkyq: '',
      jb_sfhg: ''
    },
  ],
  unit: {},
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  },
})


const listB = ref({
  kbyList: [],
  qxyList: [],
  pxyList: [],
  bzyList: [],
})
const switchAdd = ref(true)
let assignedDialogVisible = ref(false)
const selectedUsers = ref([])
const addSampleForm = ref({
  device_name: [],
})


// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
//   获取表单信息
  getWaterCapacity()
  getMethod()
  getDevicList()
});


// 获取仪器接口
const getDevicList = () => {
  CommonAPI.getdevice().then(res => {
    selectedUsers.value = res
  })
}


const fetchSearchResults = (query) => {
  if (query === '') return
  CommonAPI.getdevice({device_name: query}).then(data => {
    selectedUsers.value = data
  })
}

// 获取信息(也要粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
}


const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 7,
    record_sn: record_sn,
    // record_sn: 49,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    console.log('获取水质容量 A单', data)
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data
      waterForm.value.bdatas = Array.isArray(data.bdatas) && data.bdatas.length === 0 ? {} : data.bdatas;
      waterForm.value.unit = Array.isArray(data.unit) && data.unit.length === 0 ? {} : data.unit;
      sheetData.value = data.configs
      options.data = sheetData.value
      luckysheet.create(options);
      processedData.value = data.adatas
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      }
    }
  })
}


const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  // 调用函数
  processedData.value = filterValidSampleAdatas(processTableData(data));
  console.log('aghsduiahsuidhaiu', processedData.value);
  cdatas.value = filterValidSamples(transformData(processedData.value))
  console.log(cdatas.value)

//   调接口拿数据
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 104,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
};


// 打开分析仪器
const handleOpen = () => {
  assignedDialogVisible.value = true
}

const handleClose = () => {
  assignedDialogVisible.value = false
}


// 添加表格
const handleSureSample = () => {
  const selectedDevices = selectedUsers.value.filter(device => addSampleForm.value.device_name.includes(device.id));
  waterForm.value.device.device_name = selectedDevices.map(device => device.device_name);
  waterForm.value.device.device_model = selectedDevices.map(device => device.device_model);
  waterForm.value.device.device_number = selectedDevices.map(device => device.device_number);
  assignedDialogVisible.value = false
}

const handleDelete = (index) => {
  waterForm.value.device.device_name.splice(index, 1);
  waterForm.value.device.device_model.splice(index, 1);
  waterForm.value.device.device_number.splice(index, 1);
}

const handleSwitch = () => {
  switchAB.value = !switchAB.value
}
</script>

<template>
  <div class="card">
    <div v-show="switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">固废浸出液 原子荧光光度法分析原始记录（A面）</h1>
        <div>SXLPHJ/JL/CX-22-104</div>
        <table class="table">
          <tr>
            <td colspan="2" style="width: 9%;">任务编号</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.task_name"/>
            </td>
            <td colspan="2" style="width: 9%;">采样日期</td>
            <td colspan="3">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.sampling_time"/>
            </td>
            <td colspan="2" style="width: 9%;">分析日期</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.anal_time"/>
            </td>
            <td colspan="3">分析项目</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.fxxm">
              </el-input>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="width: 9%;">分析仪器</td>
            <td colspan="4" @click="handleOpen">
              <div v-for="(item,index) in  waterForm.device.device_name" :key="index"
                   style="display: flex;align-items: center;justify-content: space-between">
                <span>{{ item }}</span>
                <span style="cursor: pointer">
                  <el-icon size="16" @click.stop="handleDelete(index)">
                          <Coffee/>
                        </el-icon>
                </span>
              </div>
            </td>
            <td colspan="2" style="width: 10%;">仪器型号</td>
            <td colspan="3">
              <div v-for="(item,index) in waterForm.device.device_model" :key="index">{{ item }}</div>
            </td>
            <td colspan="2">仪器编号</td>
            <td colspan="4">
              <div v-for="(item,index) in waterForm.device.device_number" :key="index">{{ item }}</div>
            </td>
            <td colspan="3">环境条件</td>
            <td colspan="5">
              <div>
                <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.temperature">
                  <template #append>
                    <span style="background-color: transparent;color: black">℃</span>
                  </template>
                </el-input>
                <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.humidity">
                  <template #append>
                    <span style="background-color: transparent;color: black">%RH</span>
                  </template>
                </el-input>
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="2">分析方法</td>
            <td colspan="15">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.method"/>
            </td>
            <td colspan="3">检出限</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.limit_val">
              </el-input>
            </td>
          </tr>
          <tr>
            <td colspan="2">浸出液制备方法</td>
            <td colspan="15">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.jcyzbff">
              </el-input>
            </td>
            <td colspan="3" rowspan="3">计算公式</td>
            <td colspan="5" rowspan="3">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.js_formula"/>
            </td>
          </tr>
          <tr>
            <td colspan="2">测量条件</td>
            <td colspan="15">
              <div style="display:flex;align-items: center">
                <span style="width: 150px;">负高压：</span>
                <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.fgy"/>
                <span style="width: 150px;">灯电流：</span>
                <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.ddl"/>
              </div>

            </td>
          </tr>
          <tr>
            <td colspan="2">前处理过程</td>
            <td colspan="15">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.process">
              </el-input>
            </td>
          </tr>
          <tr>
            <td colspan="2">备注</td>
            <td colspan="23">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.notes">
              </el-input>
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width:100%;height:500px;"></div>
      </el-card>
    </div>
    <div v-show="!switchAB">
      <index :water-form="waterForm" :list-b="listB"></index>
    </div>

    <div>
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh" :handle-switch="handleSwitch"
             :get-water-capacity="getWaterCapacity" :switch-add="switchAdd" :switch-a-b="switchAB"
             :switch="true"></Index>
    </div>
    <el-dialog title="添加仪器" v-model="assignedDialogVisible" width="30%" center :before-close="handleClose">
      <el-form ref="form" :model="addSampleForm" label-width="90px">
        <el-form-item label="仪器名称：">

          <el-select v-model="addSampleForm.device_name" placeholder="请选择" filterable remote multiple
                     :remote-method="fetchSearchResults">
            <el-option
                v-for="(label, value) in selectedUsers"
                :key="value"
                :label="`${label.device_name} (${label.device_number})`"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
        <el-button @click="handleClose" style="width: 50%">取 消</el-button>
        <el-button type="primary" style="width: 50%" @click="handleSureSample">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
